package elements

import (
	"strconv"
	"yizhuoyan/go-study/pdfgo/handyio"
)

const inUseEntryKeywordByte byte = 'n'
const freeEntryKeywordByte byte = 'f'

type CrossReferenceEntry struct {
	objIndex               int64 `#:"10位对象下标"`
	objObjectVersionNumber int   `#:"5位"`
	free                   bool
}

func (this *CrossReferenceEntry) GetIndexAt() int64 {
	//去掉前置0
	return this.objIndex
}
func (this *CrossReferenceEntry) WriteEntry(w handyio.PdfRawWriter) error {
	objIndexString := strconv.FormatInt(this.objIndex, 10)
	for i := 0; i < 10-len(objIndexString); i++ {
		w.WriteByte('0')
	}
	w.WriteString(objIndexString)
	w.WriteByte(' ')
	objGnString := strconv.FormatInt(int64(this.objObjectVersionNumber), 10)
	for i := 0; i < 5-len(objIndexString); i++ {
		w.WriteByte('0')
	}
	w.WriteString(objGnString)
	w.WriteByte(' ')
	if this.free {
		w.WriteByte(freeEntryKeywordByte)
	} else {
		w.WriteByte(inUseEntryKeywordByte)
	}
	w.WriteByte(' ')
	w.WriteByte('\n')
	return nil
}

func (this *CrossReferenceEntry) ReadEntry(r handyio.PdfRawReader) error {
	offsetBytes := r.NextBytesUntilWhiteSpace()
	if len(offsetBytes) != 10 {
		return r.NotSupport("offset没有10位")
	}
	offsetBytes = cleanPrefix0(offsetBytes)
	objIndex, err := strconv.ParseInt(string(offsetBytes), 10, 64)
	if err != nil {
		return r.NotSupport("offset非数字")
	}
	this.objIndex = objIndex
	r.SkipNextWhiteSpaces()
	gnBytes := r.NextBytesUntilWhiteSpace()
	if len(gnBytes) != 5 {
		return r.NotSupport("gn没有5位")
	}
	gnBytes = cleanPrefix0(gnBytes)
	objObjectVersionNumber, err := strconv.ParseInt(string(gnBytes), 10, 64)
	if err != nil {
		return r.NotSupport("gn非数字")
	}
	this.objObjectVersionNumber = int(objObjectVersionNumber)
	r.SkipNextWhiteSpaces()
	nextByte, err := r.NextByte()
	if err != nil {
		return err
	}
	if nextByte == freeEntryKeywordByte {
		this.free = true
	}
	r.SkipNextWhiteSpaces()
	return nil
}
func cleanPrefix0(bytes []byte) []byte {
	for i, one := range bytes {
		if one != '0' {
			return bytes[i:]
		}
	}
	return bytes
}
